<?php
/**
 * Copyrigh () 2017 湖南魔工坊科技有限公司 版权所有
 * 网址：http://www.mogo.club
 * 项目名称：环球世界交易平台
 * 文件名称：Finance.php
 * 时间：2017年8月25日
 * 作者：
 */

namespace app\world\home;

use app\world\home\Common;
use app\world\model\User;
use app\world\model\Order;
use app\world\model\Configs;
use app\world\model\Goods;
use app\world\model\NewsUser;

class Capital extends Common
{


    /**
     * 配资设置
     * @author
     */
    public function index()
    {
        $id = session('home_user')['id'];
        $User = new User();
        $user_data = $User->get_find(['id' => $id]);
        //不是配资商
        if ($user_data->is_capital != 1) $this->error(@$_SESSION['is_language'] ? '參數错误' : 'Missing parameters');
        if ($this->request->post()) {
            //得到登录密码类型
            $pwd = session('home_password');
            $password = 'password' . $pwd;
            $data = input();
            if ($user_data->$password != $User->add_password($data['password'])) $this->error(@$_SESSION['is_language'] ? '密碼錯誤' : 'Password error');
            if (!is_numeric($data['capital']) || $data['capital'] < 0) $this->error(@$_SESSION['is_language'] ? '参数错误' : 'Missing parameters');
            $user_data->capital = $data['capital'];
            $user_data->save();
            $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', url('index/index'), '', 1);
        }
        $this->assign([
            'user' => $user_data,
        ]);
        return $this->fetch();
    }


    /**
     * 配资ing
     * @author
     */
    public function main()
    {
        $goods_id = input('id');
        $con = new Configs();
        $cons = $con->get_find()->toArray();
        //得到配资比例
        foreach ($cons as $key => $value) {
            if (strpos($key, 'capproportion') !== false) {
                if ($value) {
                    $con_data[] = $value;
                }
            }
        }
        $purchase_fee['purchase_fee'] = $cons['purchase_fee'];
        $user_id = session('home_user')['id'];
        $User = new User();
        $user_data = $User->get_find(['id' => $user_id]);
        $goods_data = Goods::find($goods_id);
        //如果是系统资产，则不参与配资
        if ($goods_data->user_id == 0) {
            $this->error(@$_SESSION['is_language'] ? '該產品不參與配資' : 'Parameter error', url('goods/index'), '', 1);
        }

        $this->assign([
            'goods_id' => $goods_id,
            'purchase_fee' => $purchase_fee,
            'con_data' => $con_data,
            'user_data' => $user_data,
            'goods_data' => $goods_data,
        ]);
        return $this->fetch();
    }


    /**
     * 配资商列表
     * @author
     */
    public function capital()
    {
        if ($this->request->post()) {
            $data = $_POST['data'];
            $goods_data = Goods::find($data['id']);
            if (!is_numeric($data['sum']) || $data['sum'] <= 0 || floor($data['sum']) != $data['sum']) {
                $this->error(@$_SESSION['is_language'] ? '参数错误' : 'Missing parameters', 'goods/index');
            }

            if ($goods_data->user_id == 0) {
                $this->error(@$_SESSION['is_language'] ? '該產品不參與配資' : 'Parameter error', 'goods/index');
            }
            $con = new Configs();
            $cons = $con->get_find()->toArray();
            $user_fee = $goods_data->money * $data['sum'] * $cons['purchase_fee'];  //购买手续费
            $sum_money = $goods_data->money * $data['sum'];                         //资产总值
            $user_money = $sum_money / (1 + $data['capital_pro']);                  //融资人支出余额
            $user = User::get(session('home_user')['id']);
            if ($user->money1 < $user_money + $user_fee) {
                $this->error(@$_SESSION['is_language'] ? '餘額不足' : 'Sorry, your credit is running low', 'goods/index');
            }
            $User = new User();
            //得到余额充足的配资人列表
            $list = $User->get_capital(session('home_user')['id'], $sum_money - $user_money);
            //购买信息存储到session
            $_SESSION['capital'] = $data;

            $this->assign([
                'list' => $list,
            ]);
            return $this->fetch();
        }
    }


    /**
     * 提交配资表单
     * @author
     */
    public function capital_ajax()
    {
        if ($this->request->post()) {
            $id = input('id');
            $data = $_SESSION['capital'];
            $goods_data = Goods::find($data['id']);
            if ($goods_data->user_id == 0) {
                return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '該產品不參與配資' : 'Parameter error'];
            }
            $con = new Configs();
            $cons = $con->get_find()->toArray();
            $user_fee = $goods_data->money * $data['sum'] * $cons['purchase_fee'];  //购买手续费
            $sum_money = $goods_data->money * $data['sum'];                         //资产总值
            $user_money = $sum_money / (1 + $data['capital_pro']);                  //融资人支出余额
            $user = User::get(session('home_user')['id']);
            if ($user->money1 < $user_money + $user_fee) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '餘額不足' : 'Sorry, your credit is running low'];
            $capital_user = User::get($id);
            if ($capital_user->money1 < $sum_money - $user_money) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '配資商餘額不足' : 'Sorry, your credit is running low'];

            $selling = round($goods_data->money * $data['capital_pro'] / ($data['capital_pro'] + 1), 2);   //配資商支出余额

            //创建配资订单
            $b = Order::create([
                'type' => 4,
                'pid' => $goods_data->user_id,
                'transfer_id' => $id,
                'user_id' => session('home_user')['id'],
                'goods_id' => $goods_data->id,
                'money' => $goods_data->money,
                'sum' => $data['sum'],
                'status' => 4,
                'purchase_fee' => $cons['purchase_fee'],
                'is_capital' => 1,
                'margin' => $cons['margin'],
                'selling' => $cons['selling'],
                'capital_pro' => $data['capital_pro'],
                'capital_interest' => $capital_user->capital,
                'margin_price' => ($cons['margin'] * $goods_data->money) * 0.01 + $selling,
                'selling_price' => ($cons['selling'] * $goods_data->money) * 0.01 + $selling,
            ]);

            if ($b) {
                //用户消息
                $NewsUser = new NewsUser();
                $NewsUser->title = '資產配資。Asset financing';
                $NewsUser->content = '您的配資申請正在審核。Your financing is being audited';
                $NewsUser->user_id = $user->id;
                $NewsUser->save();

                //发消息
                $User = new User();
                $on_mortgage = $User->get_no_capital($user->id, $sum_money - $user_money);
                if ($on_mortgage) {
                    foreach ($on_mortgage as $item) {
                        $infos = array();
                        $infos = [
                            'type' => 4,
                            'pid' => $goods_data->user_id,
                            'transfer_id' => $item['id'],
                            'user_id' => session('home_user')['id'],
                            'goods_id' => $goods_data->id,
                            'money' => round($goods_data->money, 2),
                            'sum' => $data['sum'],
                            'status' => 6,
                            'purchase_fee' => $cons['purchase_fee'],
                            'is_capital' => 1,
                            'margin' => '',
                            'capital_pro' => $data['capital_pro']
                        ];
                        Order::create($infos);
                    }
                }

                //减用户余额
                $user->money1 -= round($user_money + $user_fee, 2);
                $user->save();
                $f_user = User::where(['id'=>$id])->find();
                User::money_change($user->id, 0, round($user_money + $user_fee, 2), '向配資商‘'.$f_user->username.'’申請融資 Application for allocation');
                return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '操作成功' : 'Successful operation'];
            }
        }
    }


    /**
     * 配资列表
     * @author
     */
    public function capital_order()
    {
        $OrderModel = new Order();
        //查询所有股东未审核的订单
        $map['world_order.transfer_id'] = session('home_user')['id'];
        $map['world_order.type'] = 4;
        $map['world_order.status'] = ['in', [0, 2, 3, 4, 5, 6]];
        $map['world_order.surplus_sum'] = 0;
        $data1 = $OrderModel->get_list($map, '', '', 1);
        if ($data1) $data1 = collection($data1)->toArray();
        //查询所有股东审核后，未卖出的订单
        $where['world_order.transfer_id'] = session('home_user')['id'];
        $where['world_order.type'] = 4;
        $where['world_order.status'] = 1;
        $where['world_order.surplus_sum'] = ['>', 0];
        $data2 = $OrderModel->get_list($where, '', '', 1);
        if ($data2) $data2 = collection($data2)->toArray();
        $data = array_merge($data1, $data2);
        //查询卖出订单
        $mp['world_order.transfer_id'] = session('home_user')['id'];
        $mp['world_order.type'] = 5;
        $mp['world_order.status'] = ['in', [0, 1]];
        $data3 = $OrderModel->get_list($mp, '', '', 1);
        if ($data3) $data3 = collection($data3)->toArray();
        //修改创建时间,用作显示
        if ($data3) {
            foreach ($data3 as &$value) {
                $order = Order::find($value['order_id']);
                $value['create_time'] = $order->create_time;
            }
        }
        $data = array_merge($data, $data3);
        //对数据排序
        if ($data) {
            $data = my_sort($data, 'id', SORT_DESC);
        }

        foreach ($data as $k => &$v) {
            if (!$_SESSION['is_language']) {
                $v['goods_name'] = str_replace('比克', 'bike', $v['goods_name']);
            }
            $info = $OrderModel->get_capital($v['id']); //计算手续费
            $v['past_time'] = $info['past_time'];
            $v['redeem_money'] = $info['redeem_money'];
        }

        $this->assign([
            'data' => $data
        ]);
        return $this->fetch();
    }


    /**
     * 配资审核
     * @author
     */
    public function capital_order_ajax()
    {
        if ($this->request->post()) {
            $data = input();
            $order_data = Order::find($data['id']);
            $user_data = User::find(session('home_user')['id']);
            $order_user = User::find($order_data->user_id);
            if ($user_data->id != $order_data->transfer_id) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '非法操作' : 'Illegal operation'];
            $sum_money = $order_data->money * $order_data->sum;
            $NewsUser = new NewsUser();
            if ($data['type'] == 'status') {
                if ($data['value'] == 1 && $order_data->status == 4) {  //同意配资
                    $money = round($order_data->money * $order_data->sum * $order_data->capital_pro / ($order_data->capital_pro + 1), 2);
                    if ($user_data->money1 < $money) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '餘額不足' : 'Sorry, your credit is running low', 'content' => ''];
                    //用户消息
                    $NewsUser = new NewsUser();
                    $NewsUser->title = '資產配資。Asset financing';
                    $NewsUser->content = '您的配資申請通過,正在匹配資產賣家。Your financing application is passed and is being traded.';
                    $NewsUser->user_id = $order_data->user_id;
                    $NewsUser->save();

                    $order_data->is_automatic = $data['is_automatic'];
                    $order_data->status = 0;
                    $order_data->is_prompt = 0;
                    $order_data->save();

                    $user_data->money1 -= round($money, 2);
                    $user_data->save();
                    User::money_change($user_data->id, 0, round($money, 2), '同意融資人‘'.$order_user->username.'’的配資申請 Consent to funding');
                    return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '操作成功' : 'Successful operation', 'content' => ''];
                }

                if ($data['value'] == 0 && $order_data->status == 4) { //拒绝配资

                    //用户消息
                    $NewsUser->title = '資產配資。Asset financing';
                    $NewsUser->content = '您的配資申請失敗,本金已返還。The failure of financing, the return of the principal';
                    $NewsUser->user_id = $order_data->user_id;
                    $NewsUser->save();

                    $order_data->status = 5;
                    $order_data->save();

                    $fee_money = $sum_money * $order_data->purchase_fee;
                    $money = $sum_money / (1 + $order_data->capital_pro);
                    $order_user->money1 += $fee_money + $money;
                    $order_user->save();

                    User::money_change($order_user->id, 1, $fee_money + $money, '配資商拒絕‘'.$user_data->username.'’您的融資申請 Misallocation');
                    return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '操作成功' : 'Successful operation', 'content' => ''];
                }
                return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '非法操作' : 'Illegal operation'];
            }
            if ($data['type'] == 'sell') { //平仓

                $Order = new Order();
                $order_datas = $Order->get_find(['world_order.id' => $data['id'], 'world_order.type' => 4, 'world_order.transfer_id' => session('home_user')['id']]);
                $order_datas1 = $order_datas->toArray();
                if ($order_datas->surplus_sum == 0) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '該資產已賣出' : 'The asset has been sold', 'content' => ''];
                $order_selling = round(($order_datas->goods_money * $order_datas->surplus_sum + $order_datas->money3), 2);
                if ($order_selling > $order_datas->selling_money) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '資產價值未達到平倉綫' : 'The value of the assets did not reach the level of the warehouse', 'content' => ''];
                $con = new Configs();
                $con_data = $con->get_find('purchase_fee,sell_fee');

                $info['order_id'] = $order_datas1['id'];
                $info['type'] = 5;
                $info['pid'] = $order_datas1['pid'];
                $info['transfer_id'] = $order_datas1['transfer_id'];
                $info['user_id'] = $order_datas1['user_id'];
                $info['goods_id'] = $order_datas1['goods_id'];
                $info['money'] = $order_datas1['money'];
                $info['money2'] = $order_datas1['goods_money'];
                $info['money3'] = $order_datas1['money3'];
                $info['sum'] = $order_datas1['surplus_sum'];
                $info['actual_sum'] = $order_datas1['surplus_sum'];
                $info['surplus_sum'] = $order_datas1['surplus_sum'];
                $info['purchase_fee'] = $order_datas1['purchase_fee'];
                $info['sell_fee'] = $con_data->sell_fee;
                $info['is_capital'] = $order_datas1['is_capital'];
                $info['margin'] = $order_datas1['margin'];
                $info['selling_money'] = $order_datas1['selling_money'];
                $info['margin_money'] = $order_datas1['margin_money'];
                $info['capital_pro'] = $order_datas1['capital_pro'];
                $info['is_automatic'] = $order_datas1['is_automatic'];
                $info['capital_interest'] = $order_datas1['capital_interest'];
                $info['time'] = $order_datas1['time'];
                $info['is_selling'] = 1;  //是否平仓
                $info['is_force'] = 1;  //是否平仓
                $Order->add_order($info);
                $order_datas->surplus_sum = 0;
                $order_datas->is_selling = 1;  //是否平仓
                $order_datas->is_force = 1;  //是否平仓
                $order_datas->selling_price = $order_datas1['selling_price'];
                $order_datas->margin_price = $order_datas1['margin_price'];
                $order_datas->save();

                $NewsUser->title = '資產配資。Asset financing';
                $NewsUser->user_id = $order_data['user_id'];
                $NewsUser->content = '您賣出的配資資產正在匹配資產買家。The assets you sell are matching the asset buyers  ';
                $NewsUser->save();
                return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '您賣出的配資資產正在匹配資產買家' : 'The assets you sell are matching the asset buyers'];

            }
        }
    }

    /**
     * 配资资产
     * @author
     */
    public function lists()
    {
        $OrderModel = new Order();
        //查询所有股东未审核的订单
        $map['world_order.user_id'] = session('home_user')['id'];
        $map['world_order.type'] = 4;
        $map['world_order.status'] = ['in', [0, 2, 3, 4, 5]];
        $map['world_order.surplus_sum'] = 0;
        $data1 = $OrderModel->get_list($map, '', '', 1);
        if ($data1) $data1 = collection($data1)->toArray();
        //查询所有股东审核后，未卖出的订单
        $where['world_order.user_id'] = session('home_user')['id'];
        $where['world_order.type'] = 4;
        $where['world_order.status'] = 1;
        $where['world_order.surplus_sum'] = ['>', 0];
        $data2 = $OrderModel->get_list($where, '', '', 1);
        if ($data2) $data2 = collection($data2)->toArray();
        $data = array_merge($data1, $data2);
        //查询卖出订单
        $mp['world_order.user_id'] = session('home_user')['id'];
        $mp['world_order.type'] = 5;
        $mp['world_order.status'] = ['in', [0, 1]];
        $data3 = $OrderModel->get_list($mp, '', '', 1);
        if ($data3) $data3 = collection($data3)->toArray();
        //修改创建时间,用作显示
        if ($data3) {
            foreach ($data3 as &$value) {
                $order = Order::find($value['order_id']);
                $value['create_time'] = $order->create_time;
            }
        }
        $data = array_merge($data, $data3);
        //对数据排序
        if ($data) {
            $data = my_sort($data, 'id', SORT_DESC);
        }


        foreach ($data as $k => &$v) {
            if (!$_SESSION['is_language']) {
                $v['goods_name'] = str_replace('比克', 'bike', $v['goods_name']);
            }
            $info = $OrderModel->get_capital($v['id']);
            $v['past_time'] = $info['past_time'];
            $v['redeem_money'] = $info['redeem_money'];
        }


        Order::update([
            'is_prompt' => 1
        ], ['user_id' => session('home_user')['id']]);


        $this->assign([
            'data' => $data
        ]);
        return $this->fetch();
    }


    /**
     * 提交保證金-提醒
     * @author
     */
    public function bond_ajax()
    {
        if ($this->request->post()) {
            $id = input('id');
            $Order = new Order();
            $order_data = $Order->get_find(['world_order.id' => $id, 'world_order.type' => 4, 'world_order.user_id' => session('home_user')['id']]);
            if (!$order_data) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '資產不存在' : 'Non-existent', 'content' => ''];
            $order_margin = round(($order_data->goods_money * $order_data->surplus_sum + $order_data->money3), 2);
            if ($order_margin >= $order_data->margin_money) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '資產價值未達到補倉綫' : 'The value of the assets has not reached the margin line', 'content' => ''];
            $money = $order_data->margin_money - ($order_data->money3 + $order_data->goods_money * $order_data->surplus_sum);
            return ['code' => 1, 'msg' => '', 'content' => $money];
        }
    }


    /**
     * 提交保證金
     * @author
     */
    public function bond()
    {
        if ($this->request->post()) {
            $id = input('id');
            $Order = new Order();
            $order_data = $Order->get_find(['world_order.id' => $id, 'world_order.type' => 4, 'world_order.user_id' => session('home_user')['id']]);
            if (!$order_data) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '資產不存在' : 'Non-existent', 'content' => ''];
            $order_margin = round(($order_data->goods_money * $order_data->surplus_sum + $order_data->money3), 2);
            if ($order_margin >= $order_data->margin_money) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '資產價值未達到補倉綫' : 'The value of the assets has not reached the margin line', 'content' => ''];
            $money = $order_data->margin_money - ($order_data->money3 + $order_data->goods_money * $order_data->surplus_sum);
            $user_data = User::find(session('home_user')['id']);
            if ($user_data->money1 < $money) {
                return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '餘額不足' : 'Sorry, your credit is running low', 'content' => ''];
            }
            $user_data->money1 -= $money;
            $user_data->save();

            $t_user = User::find($order_data->transfer_id);

            User::money_change($user_data->id, 0, $money, '繳納配資商‘'.$t_user->username.'’融資的資產‘'.$order_data->goods_name.'’的保證金 Pay deposit');
            Order::update(['bond_prompt' => 0], ['id' => $id]);
            db('world_order')->where('id', $id)->setInc('money3', $money);
            return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '操作成功' : 'Successful operation'];
        }

    }

    /**
     * 融资人卖出配资资产
     * @author
     */
    public function sell()
    {
        if ($this->request->post()) {
            $OrderModel = new Order();
            $NewsUser = new NewsUser();
            $info = input();
            $order = $OrderModel->get_find(['world_order.id' => $info['id'], 'world_order.type' => 4, 'world_order.user_id' => session('home_user')['id']]);
            if (!$order) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '資產不存在' : 'Commodity does not exist'];
            if ($order->surplus_sum == 0) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '該資產已賣出' : 'The asset has been sold', 'content' => ''];
            $order_data = $order->toArray();

            $con = new Configs();
            $money = $order->goods_money * $order->surplus_sum + $order->money3;

            if ($money >= $order_data['selling_money']) { //是否平仓
                $is_selling = 0;
            } else {
                $is_selling = 1;
            }

            $con_data = $con->get_find('purchase_fee,sell_fee');
            $data['order_id'] = $order_data['id'];
            $data['type'] = 5;
            $data['pid'] = $order_data['pid'];
            $data['transfer_id'] = $order_data['transfer_id'];
            $data['user_id'] = $order_data['user_id'];
            $data['goods_id'] = $order_data['goods_id'];
            $data['money'] = $order_data['money'];
            $data['money2'] = $order_data['goods_money'];
            $data['money3'] = $order_data['money3'];
            $data['sum'] = $order_data['surplus_sum'];
            $data['actual_sum'] = $order_data['surplus_sum'];
            $data['surplus_sum'] = $order_data['surplus_sum'];
            $data['purchase_fee'] = $order_data['purchase_fee'];
            $data['sell_fee'] = $con_data->sell_fee;
            $data['is_capital'] = $order_data['is_capital'];
            $data['margin'] = $order_data['margin'];
            $data['selling_money'] = $order_data['selling_money'];
            $data['margin_money'] = $order_data['margin_money'];
            $data['capital_pro'] = $order_data['capital_pro'];
            $data['is_automatic'] = $order_data['is_automatic'];
            $data['capital_interest'] = $order_data['capital_interest'];
            $data['time'] = $order_data['time'];
            $data['is_selling'] = $is_selling;  //是否平仓
            $data['selling_price'] = $order_data['selling_price'];
            $data['margin_price'] = $order_data['margin_price'];

            $OrderModel->add_order($data);
            $order->surplus_sum = 0;
            $order->is_selling = $is_selling;
            $order->save();

            $NewsUser->title = '資產配資。Asset financing';
            $NewsUser->user_id = $order_data['user_id'];
            $NewsUser->content = '您賣出的配資資產正在匹配資產買家。The assets you sell are matching the asset buyers  ';
            $NewsUser->save();
            return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '您賣出的配資資產正在匹配資產買家' : 'The assets you sell are matching the asset buyers'];
        }
        return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '非法操作' : 'Illegal operation'];
    }
}